package cn.hackertools.staticresource.utils;


import cn.hackertools.staticresource.entity.FileResult;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class FileHandler {

    @Value("${static-resouce-file-path}")
    private String rootPath;
    public List<FileResult.ListBean> readFiles(String path,String search,String all){

        List<FileResult.ListBean> datas=new ArrayList<FileResult.ListBean>();
        //要打开的目录
        File file=new File(path);
        System.out.println(path);
        File[] files =new File[0];
        System.out.println("all:"+all);
        if(all==null||"".equals(all))
        {
            files =file.listFiles();
        }else{
            List<File> files1 = getFiles(file);
            files1.removeIf(p->p.getPath().equals(path));
            files= new File[files1.size()];
            files1.toArray(files);
        }

        System.out.println(search);
        for(File temp:files)
        {
            //如果搜素的话
            if(search!=null&&!"".equals(search))
            {
                if(temp.getName().indexOf(search)==-1)
                {
                    continue;
                }
            }
            datas.add(addJsonFile(temp));
        }

        return datas;
    }


    private FileResult.ListBean addJsonFile(File temp){

        FileResult.ListBean listBean=new FileResult.ListBean();
        listBean.setAccept(777);
        listBean.setCaret(false);
        listBean.setComposer(0);
        listBean.setDown_id(0);
        listBean.setExt("");
        listBean.setFilename(temp.getName());
        listBean.setLink("");
        listBean.setMtime(temp.lastModified());
        listBean.setPs("");
        listBean.setShell(false);
        listBean.setSize(0);
        if(!temp.isFile())
        {
            listBean.setType("dir");
        }else{
            listBean.setType("file");
        }
        return listBean;
    }

    public String readBody(String path)
    {
        String result=null;
        StringBuilder tempBuf=new StringBuilder();
        try {
            FileInputStream fileInputStream=new FileInputStream(path);
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(fileInputStream,"utf-8"));
            String lineStr=null;
            while((lineStr=bufferedReader.readLine())!=null)
            {
                tempBuf.append(lineStr+"\r\n");
            }
            bufferedReader.close();
            fileInputStream.close();
            result=tempBuf.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return result;
    }


    public void writeBufForFile(String path, ServletOutputStream outputStream)
    {
        FileInputStream fileInputStream=null;
        try {
            fileInputStream=new FileInputStream(path);
            byte[] buf=new byte[1024];
            int readLine=-1;
            while((readLine=fileInputStream.read(buf))!=-1)
            {
                outputStream.write(buf,0,readLine);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }


    }


    public boolean writeFileBody(String data,String path,String encoding){
        try {
            FileOutputStream fileOutputStream=new FileOutputStream(path);
            BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(fileOutputStream,encoding));
            bufferedWriter.write(data);
            bufferedWriter.close();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }

    public boolean deleteDir(String dirPath)
    {
        boolean flag=true;
        File dir=new File(dirPath);
        if(dir.exists()&&!dir.isFile())
        {
            List<File> files = getFiles(dir);
            for(File temp:files)
            {
                if(!temp.delete())
                {
                    flag=false;
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * 目录路径
     * @param dirPaht  目录路径
     * @return
     */
    public List<File> getFiles(File dirPaht)
    {

        List<File> files=new ArrayList<>();

        for(File file:dirPaht.listFiles())
        {
            if(file.isFile()&&file.exists())
            {
                files.add(file);
            }else if(file.isDirectory()&&file.exists())
            {
                List<File> files1 = getFiles(file);
                files.addAll(files1);

            }

        }
        files.add(dirPaht);
        return files;
    }

}
